package com.code2roc.jarmanage.servlet.pfmanage;



import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.model.ProjectDO;
import com.code2roc.jarmanage.util.ConvertUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class FileDownLoadServlet  extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String prefix = URLDecoder.decode(req.getParameter("prefix"));
        String fileName = URLDecoder.decode(req.getParameter("fileName"));
        String projectID = ConvertUtil.convert2String(req.getParameter("projectID"));
        ProjectDO projectDO = ProjectDB.selectOne(projectID);
        String basePath = projectDO.getJarPackagePath()  + File.separator;
        String filePath = basePath + prefix;
        filePath = filePath + File.separator + fileName;
        File file = new File(filePath);
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Disposition", "filename=" + URLEncoder.encode(fileName, "utf-8"));
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        byte[] buff = new byte[(int) file.length()];
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        try {
            outputStream = resp.getOutputStream();
            bufferedInputStream = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bufferedInputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, i);
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
